<template>
  <div class="drag-index">

    <el-row class="drag-row">
      <el-col :span="7" class="drag-left">

        <draggable :list="dragList" ghost-class="ghostA" :force-fallback="true"
                   :group="{ name: 'list', pull: 'clone' }" :sort="false" itemKey="id">
          <template #item="{ element }">
            <div class="drag-w-left">
              <el-icon class="drag-icon" size="22">
                <ChromeFilled/>
              </el-icon>
              <!--              <img class="drag-icon" src="@/assets/images/serious/right-light.png" alt="">-->
              <div class="drag-yin">
                <div class="title-box">
                  <span class="title-text">{{ element.id }}</span>
                  <div class="title-btn">
                    <span class="btn" @click="updateDrag(element)">修改</span>
                    <span class="btn" @click="hiddenDrag(element)">隐藏</span>
                  </div>
                </div>
                <!-- 小标题展示 -->
                <div v-if="!element.tableData && !element.text" class="move">
                  <div v-for="(value, key) in element" :key="key">
                    <div v-if="!['id', 'tableData', 'tableHeader'].includes(key)" v-show="value != null"
                         style="margin-right: 6px">
                      {{ value }}
                    </div>
                  </div>
                </div>
                <span class="textStyle" v-show="element.text != null">{{ element.text }}</span>
                <span class="move" v-show="element.tableData != null">详情请拖到右框查看</span>
              </div>
            </div>
          </template>
        </draggable>


        <el-button @click="handleAdd" class="button-add" round type="primary" :icon="Plus" color="#5895C2">添加
        </el-button>

      </el-col>

      <el-col :span="16" style="width: 100%;height: 100%;">

        <div class="drag-content" ref="exportContent">

          <h2 style="text-align: center;line-height: 100px;">小C有限公司</h2>
          <h3 style="text-align: center;">抑郁症筛查量表(PHQ-9)结果分析报告</h3>
          <!--          拖拽模板报告文档字段需求-->
          <!--          数组形式：-->
          <!--          1.每一个对象必须含有一个相同的字段，作为模板标题使用。-->
          <!--          2.图表内容tableDate数组， 图表标题栏tableHeader对象。tableDate和tableHeader字段名一致。其中，编号(id)和第二个标题栏名称(name)尽量固定字段。-->
          <!--          3.多文本统一以固定字段命名。-->
          <!--          4.只要是图标，多文本（有数据的情况下）所在的对象内，其他字段默认不展示。添加模板时需注意。-->

          <!-- //拖拽的结果，B组-->
          <draggable :list="widgetList" ghost-class="ghosts" itemKey="id" :force-fallback="true" group="list"
                     :fallback-class="true" :fallback-on-body="true" animation="300"
                     style="width: 100%;min-height: 60%;">
            <template #item="{ element }">
              <div class="drag-wrap">

                <div class="content-little-title">
                  <div class="left-content">
                    <div class="line-content"></div>
                    <h4 class="content-id">{{ element.id }}</h4>
                    <div class="long-line-cont"></div>
                    <div class="english-content">xxx xxx xx xxxx</div>
                  </div>
                  <img class="right-content" src="@/assets/right-light.png" alt="暂无">
                </div>


                <div style="width:100%;height:20px;display: table!important">
                  <div style="display: table-cell!important;text-align:left">去去去2</div>
                  <div style="display: table-cell!important;text-align:right;float: right">啦啦啦</div>
                </div>

                <!-- 键值对展示  之前-->
                <!--                <div class="drag-list">-->
                <!--                  <div class="m-right">-->
                <!--                    <div>{{ element.name }}</div>-->
                <!--                  </div>-->
                <!--                  <div class="m-right">-->
                <!--                    <div>{{ element.idCard }}</div>-->
                <!--                  </div>-->
                <!--                  <div class="m-right">-->
                <!--                    <div>{{ element.age }}</div>-->
                <!--                  </div>-->
                <!--                </div>-->
                <!--                <div class="drag-list">-->
                <!--                  <div class="m-right">-->
                <!--                    <div>{{ element.address }}</div>-->
                <!--                  </div>-->
                <!--                  <div class="m-right">-->
                <!--                    <div>{{ element.tel }}</div>-->
                <!--                  </div>-->
                <!--                </div>-->

                <!-- 键值对展示 替换 -->
                <el-row v-if="!element.tableData && !element.text && !element.textarea" class="drag-list-other aaaa">
                  <el-col :span="8" v-for="(value, key) in element" :key="key">
                    <div v-if="!['id', 'tableData', 'tableHeader'].includes(key)" v-show="value != null">
                      {{ value }}
                    </div>
                  </el-col>
                </el-row>


                <!-- 文本段落渲染 -->
                <div class="drag-text" v-if="element.text">
                  {{ element.text }}
                </div>


                <div class="drag-list" v-if="element.textarea">
                  {{ element.textarea }}：
                </div>


                <el-table :data="tableDataList">
                  <el-table-column prop="name" label="姓名"/>
                  <el-table-column prop="age" label="年龄"/>
                  <el-table-column prop="age" label="年龄"/>
                  <el-table-column prop="age" label="年龄"/>
                </el-table>

                <div v-show="element.tableData" style="width: 100%;font-size: 0.85vw;">
                  <p style="line-height: 50px;"> 测评结果：</p>
                  <el-table
                      :data="element.tableData"
                      :cell-style="{textAlign: 'center'}"
                      :header-cell-style="{textAlign: 'center'}"
                      border
                  >
                    <el-table-column
                        v-for="(label, prop) in element.tableHeader" :key="prop" :prop="prop" :label="label">
                      <template #default="scope"
                                v-if="element.tableHeader.name !== label && element.tableHeader.id !== label">
                        <el-icon size="25" v-show="scope.row[prop]">
                          <Check/>
                        </el-icon>
                      </template>
                    </el-table-column>

                  </el-table>
                </div>


              </div>
            </template>
          </draggable>


          <div class="drag-footer">
            <p class="name-footer">主试者（签字）：</p>
            <p class="date-footer">日期：2025年3月14日</p>
          </div>


        </div>
      </el-col>

    </el-row>


    <div style="position: absolute;right:75px;top: 25px;width: 80px;height: 80px;overflow: hidden;"
         @click="deleteFn">
      <img src="@/assets/deleteIcons.png" alt="删除"
           style="width: 40px;height: 40px;position:absolute;right: 10px;top: 10px; z-index: 1000;"/>
      <draggable :list="deleteList" itemKey="id" :force-fallback="true" group="list"
                 :fallback-class="true" :fallback-on-body="true" animation="300"
                 style="width: 100%;height: 100%;position: absolute;top: 0;left: 0;color: #e0f1ef;">
        <template #item="{ element }">
          <div>
            {{ element.a }}
          </div>
        </template>
      </draggable>
    </div>

    <div style="position: absolute;right: 35px;top: 35px;width: 40px;height: 40px;overflow: hidden"
         @click="exportFn">
      <img src="@/assets/exportIcons.png" alt="删除" style="width: 100%;height: 100%;"/>
    </div>

    <!-- 添加或修改模板信息对话框 -->
    <el-dialog :title="title" v-model="open" width="550px" append-to-body>
      <el-form ref="patientRef" :model="form" :rules="rules" label-width="100px">

        <el-form-item label="模块类型" prop="moduleName">
          <el-radio-group v-model="form.type">
            <el-radio value="0">表格</el-radio>
            <el-radio value="1">多文本</el-radio>
            <el-radio value="2">其他</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="模块名称" prop="moduleName">
          <el-input v-model="form.moduleName" placeholder="请输入模块名称"/>
        </el-form-item>

        <div v-if="form.type == 2">

          {{ inputs }}
          <el-form-item label="基础信息字段" prop="name">
            <el-input v-for="(input, index) in inputs" :key="index" v-model="inputs[index]" placeholder="请输入内容"
                      @input="handleInput(index)" class="dynamic-input"/>
          </el-form-item>
        </div>

        <div v-if="form.type == 0">

          <el-form-item label="表格横坐标" prop="name">
            <el-input v-model="form.name" placeholder="请输入字段名称"/>
          </el-form-item>

          <el-form-item label="表格纵坐标" prop="name">
            <el-input v-model="form.name" placeholder="请输入字段名称"/>
          </el-form-item>

        </div>
        <div v-if="form.type == 1">
          <el-form-item label="多文本" prop="name">
            <el-input v-model="form.name" placeholder="请输入多文本字段名"/>
          </el-form-item>
        </div>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup lang="js">
import draggable from 'vuedraggable'
import {reactive, h, ref, toRefs} from "vue";
import {Check, ChromeFilled} from "@element-plus/icons-vue";
import {Plus} from '@element-plus/icons-vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {asBlob} from 'html-docx-js-typescript'
import {saveAs} from 'file-saver'


const data = reactive({
  form: {type: 0},
  rules: {
    moduleName: [{required: true, message: "模板姓名不能为空", trigger: "blur"}],
    idCard: [{required: true, message: "身份证号不能为空", trigger: "blur"}],
    phone: [
      {required: true, message: "手机号不能为空", trigger: "blur"},
      {min: 11, max: 11, message: "请输入11位手机号码", trigger: "blur"},
      {pattern: /^1[3456789]\d{9}$/, message: "请输入正确的手机号码",},
    ],
    guardianName: [{required: true, message: "监护人姓名不能为空", trigger: "blur"}],
    guardianPhone: [
      {required: true, message: "监护人电话不能为空", trigger: "blur"},
      {min: 11, max: 11, message: "请输入11位手机号码", trigger: "blur"},
      {pattern: /^1[3456789]\d{9}$/, message: "请输入正确的手机号码",},],
    education: [{required: true, message: "教育水平不能为空", trigger: "blur"},],
    birthday: [{required: true, message: "请选择生日", trigger: "blur"}],
  },
});
const {form, rules} = toRefs(data);
const title = ref("");
const open = ref(false);


const inputs = ref(['']) // 初始包含一个空输入框

const handleInput = (index) => {
  // 当在最后一个输入框输入内容时，自动添加新输入框
  if (index === inputs.value.length - 1 && inputs.value[index].trim()) {
    inputs.value.push('')
  }
}


/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  form.value.type = 0
  title.value = "添加模板信息";
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    gender: null,
    phone: null,
    birthday: null,
    idCard: null,
    isEnabled: null,
    address: null,
    unit: null,
    education: null,
    employeeId: null,
    delFlag: null,
    peopleType: null,
    projectIds: null,
    createdTime: null,
    updatedTime: null,
    createdUserId: null,
    createdUserName: null,
  };
}

/** 提交按钮 */
function submitForm() {


}

//左边
let dragList = reactive([
  {
    name: "姓名", idCard: '身份证号', age: '年龄', address: '家庭地址', tel: '联系方式',
    id: '个人基本信息',
  }, {
    wx: "是否有妄想症",
    ld: '是否有妄想症',
    age: '是否啦啦啦',
    aaa: '是否哈哈哈哈',
    az: '是否哈哈哈哈',
    id: '普通',
    text: '',
  },
  {
    id: '报告说明',
    text: "《心理研究》是经国家新闻出版总署批准，由河南大学主办的综合性心理学学术期刊，刊号为ISSN 2095-1159，CN 41-1393/B，2008年起在国内外公开发行，双月刊，逢双月1日出版发行，邮发代号：36-83。本刊包括理论论坛、基础研究、应用研究、学校心理研究等栏目，主要刊登基础心理学、发展与教育心理学和应用心理学各领域中具有创新性的研究报告、论文、综述等。热诚欢迎国内外心理学研究者踊跃投稿。",
  },
  {
    id: '表表表',
    tableData: [
      {id: 1, name: '兴趣', none: true, little: false, middle: false, weight: false,},
      {id: 2, name: '心情低落', none: false, little: true, middle: false, weight: false,},
      {id: 3, name: '睡眠障碍', none: false, little: false, middle: true, weight: false,},
      {id: 4, name: '胃口不好或吃太多', none: true, little: false, middle: false, weight: false,},
      {id: 5, name: '注意力障碍', none: false, little: false, middle: false, weight: true,},
      {id: 6, name: '行动或语速迟缓，或烦躁不安', none: false, little: true, middle: false, weight: false,},
      {id: 7, name: '又自我伤害或轻生观念', none: true, little: false, middle: false, weight: false,},
    ],
    tableHeader: {
      id: '编号',
      name: '症状项目',
      none: "没有",
      little: "中度",
      middle: "啦啦",
      weight: "重度",
    },
  },
  {
    tableData: null,
    tableHeader: {},
    textarea: "备注",
    address: null,
    tel: null,
    id: '医生说明',
  },
])


//右边
const widgetList = reactive([])


// 删除
const deleteList = reactive([{a: 0}])
const deleteFn = () => {
  ElMessageBox({
    title: '提示',
    message: h('p', null, [
      h('span', null, '请将不需要的模板 '),
      h('i', {style: 'color: teal'}, ' 拖 拽 到 '),
      h('span', null, ' 垃圾桶里来'),
    ]),
  })

}


const updateDrag = (val) => {
  console.log(val)
  reset();
  // const _id = row.id || ids.value;

  // getPatient(_id).then((response) => {
  //   form.value = response.data;
  //   form.value.isEnabled = form.value.isEnabled + "";
  //   form.value.gender = form.value.gender + "";
  open.value = true;
  title.value = "修改模板信息";
  // });
}
const hiddenDrag = (val) => {
  console.log(val)

}


// 导出内容DOM引用
const exportContent = ref(null)

// 表格示例数据
const tableDataList = ref([
  {name: '张三张三张三张三张三张三张三', age: 25},
  {name: '李四', age: 30}
])

// 导出功能实现
const exportFn = async () => {

  // 1. 获取需要导出的HTML内容
  const rawElement = exportContent.value.$el || exportContent.value
  let contentElement = rawElement.cloneNode(true)
  // let contentElement = exportContent.value.cloneNode(true)

  // 处理浮动元素
  const floatElements = contentElement.querySelectorAll('[style*="float"]')
  floatElements.forEach(el => {
    const floatValue = el.style.cssText.match(/float:\s*(\w+)/)[1]
    el.style.cssText = `
    display: inline-block!important; /* 替换浮动为行内块 */
    width: auto!important;
    margin-${floatValue === 'left' ? 'right' : 'left'}: auto!important; /* 模拟浮动对齐 */
    ${el.style.cssText.replace(/float:\s*\w+;?/, '')} /* 保留原有其他样式 */
  `
  })

// 修复父容器高度
  const parent = contentElement.querySelector('div[style*="height"]')
  parent.style.overflow = 'hidden' // 触发BFC

  // 处理Element表格布局
  const tables = contentElement.querySelectorAll('.el-table')
  tables.forEach(table => {
    table.style.cssText = 'display: table!important; width: 100%!important;'
    table.querySelectorAll('.el-table__row').forEach(row => {
      row.style.display = 'table-row!important'
    })
  })

  // 克隆元素后执行样式覆盖
  const rows = contentElement.querySelectorAll('.el-row')
  rows.forEach(row => {
    row.style.cssText = `
    display: block !important;
    width: 100% !important;
    margin: 0 !important
  `

    // 转换列布局为传统表格
    const cols = row.querySelectorAll('.el-col')
    cols.forEach(col => {
      col.style.cssText = `
      float: left !important;
      width: ${(100 / 24) * parseInt(col.className.match(/el-col-(\d+)/)[1])}% !important;
      padding: 5px !important
    `
    })
  })

  // 处理图片（需转base64）
  const images = contentElement.querySelectorAll('img')
  for (const img of images) {
    if (!img.src.startsWith('data:')) {
      const response = await fetch(img.src)
      const blob = await response.blob()
      img.src = await new Promise(resolve => {
        const reader = new FileReader()
        reader.onload = () => resolve(reader.result)
        reader.readAsDataURL(blob)
      })
    }
  }

// 处理条件渲染的内容
  const emptyCheck = contentElement.querySelector('.drag-list-other')
  if (emptyCheck) {
    console.log('111111111111')
    emptyCheck.querySelectorAll('div').forEach(div => {
      div.style.cssText = `
      min-height: 20px;
      max-width: 80px;
      border: 1px dashed #eee;
      padding: 8px !important
    `
    })
  }


  // 2. 处理Element Plus组件样式
  const globalStyles = `
  div {
    box-sizing: border-box!important;
    border-collapse: collapse!important;
  }
  /* 转换浮动为表格布局 */
  @media word {
    [style*="float:left"], [style*="float:right"] {
      display: table-cell!important;
      float: none!important;
    }
  }
  /* 强制表格布局 */
  .el-row {
    display: table !important;
    width: 100% !important;
    table-layout: fixed;
  }

  .el-col {
    display: table-cell !important;
    border: 1px solid #ddd !important;
    vertical-align: top;
  }

  /* 清除浮动残留 */
  .el-row::after {
    content: "";
    display: table;
    clear: both;
  }
  /* 基础字体 */
  body { font-family: "宋体", SimSun; font-size: 14pt; }

  /* 表格样式 */
  table {
    border-collapse: collapse;
    width: 100%;
    margin: 10pt 0;
  }
  td, th {
    border: 1pt solid #000;
    padding: 5pt 8pt;
    vertical-align: top;
  }

  /* Element组件覆盖 */
  .el-input__inner,
  .el-textarea__inner {
    border: none!important;
    padding: 0!important;
  }
  .el-table--border {
    border-right: 1pt solid #000;
    border-bottom: 1pt solid #000;
  }
`

  // 3. 构建完整HTML结构
  const fullHTML = `
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8">
        <style>${globalStyles} </style>
      </head>
      <body style="width: 100%!important; margin: 0!important">
        ${contentElement.innerHTML}
      </body>
    </html>
  `


  // 4. 转换为Word文档
  try {
    const blob = await asBlob(fullHTML, {
      orientation: 'portrait',
      margins: {top: 1000, right: 800, bottom: 1000, left: 800},
      font: 'SimSun'  // 强制中文字体
    })

    // 5. 保存文件
    saveAs(blob, 'exported-document.docx')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('文档导出失败')
  }
}

</script>


<style scoped lang="less">


.el-table {
  display: table !important;
  width: 100% !important;
  table-layout: fixed !important;
}

.el-table__body-wrapper,
.el-table__header-wrapper {
  overflow: visible !important;
}

.drag-index {
  width: calc(100vw - 50px);
  height: calc(100vh - 50px);
  user-select: none;
  background: #B8E5E3;
  padding: 25px;

  .drag-row {
    width: 100%;
    height: 100%;
    background: #e0f1ef;
    border-radius: 8px;
    box-sizing: border-box;
    position: relative;

    .drag-left::-webkit-scrollbar {
      display: none; /* 隐藏滚动条 */
    }

    .drag-left {
      width: calc(100% - 20px);
      height: calc(100% - 20px);
      overflow: auto;
      margin: 10px;
      background: #87CCC7;
      border-radius: 6px;
      box-shadow: 5px 0 5px rgba(0, 0, 0, 0.3);
      color: #FFFFFF;

      .drag-w-left {
        display: flex;
        align-items: flex-start;
        width: 100%;
        margin-bottom: 20px;
        padding: 20px 0;
        box-shadow: 0 8px 5px rgb(123, 193, 192);

        .drag-icon {
          max-width: 5%;
          height: auto;
          object-fit: contain;
          margin-left: 4%;
          margin-right: 2%;
        }

        .drag-yin {
          width: 83%;

          .title-box {
            width: 100%;
            display: flex;
            justify-content: space-between;
            align-items: end;
            border-bottom: 2px solid #9ddad6;
            margin-bottom: 15px;

            .title-text {
              font-size: 0.95vw;
            }

            .title-btn {
              font-size: 0.55vw;

              .btn {
                margin-left: 10px;
              }
            }
          }

          .move {
            font-size: 0.6vw;
            display: flex;
          }

          .textStyle {
            font-size: 0.6vw;
            display: -webkit-box; /* 使用伸缩盒子模型 */
            -webkit-box-orient: vertical; /* 垂直排列子元素 */
            -webkit-line-clamp: 2; /* 显示三行文本 */
            overflow: hidden; /* 隐藏溢出部分 */
            text-overflow: ellipsis; /* 超出部分显示省略号 */

          }
        }
      }

      .button-add {
        color: #FFFFFF;
        position: absolute;
        bottom: 30px;
        left: 30px;
        z-index: 99;
      }
    }

    .drag-content {
      width: 100%;
      height: 96%;
      overflow: auto;
      margin: auto;
      color: #59a29b;

      .drag-footer {
        margin-top: 60px;
        width: 100%;
        height: 100px;
        position: relative;
        font-size: 0.85vw;

        .name-footer {
          position: absolute;
          top: 0;
          right: 20%;
        }

        .date-footer {
          position: absolute;
          bottom: 0;
          right: 10%;
        }
      }

      .drag-wrap {
        width: 85%;
        margin: 0 auto;
        margin-bottom: 30px;

        .content-little-title {
          width: 100%;
          display: flex;
          color: #59a29b;

          .left-content {
            width: calc(100% - 66px);

            .content-id {
              font-size: 1vw;
            }

            .english-content {
              font-size: 0.7vw;
            }

            .line-content {
              background: linear-gradient(to right, #bee3e0, #bee3e0, #FFFFFF, #bee3e0);
              width: 60px;
              height: 4px;
              margin-bottom: 10px;
              border-radius: 10px;
            }

            .long-line-cont {
              width: 100%;
              height: 1px;
              background: #86cac5;
              margin: 6px 0;
            }
          }

          .right-content {
            width: 65px;
            height: 65px;
            margin-top: 13px;
            object-fit: cover;
          }


        }

        .drag-list {
          display: flex;
          line-height: 50px;
          font-size: 0.85vw;

          .m-right {
            min-width: 32%;
            max-width: 100%;
          }
        }

        .drag-list-other {
          width: 100%;
          line-height: 50px;
          font-size: 0.85vw;
        }

        .drag-text {
          line-height: 25px;
          font-size: 0.85vw;
        }


      }
    }

    .drag-content::-webkit-scrollbar {
      display: none; /* 隐藏滚动条 */
    }

    .ghostA {
      opacity: 0.5;
      border: 2px dashed #409eff;
      background: #f5f7fa;
    }

    .ghosts {
      opacity: 0.5;
      border: 2px dashed #16958f;
      background: #f5f7fa;
    }


  }
}
</style>
